import 'dart:io';

class AnsiColor {
  /// ANSI控制序列导入器，向终端发出新的设置信号。
  static const ansiEsc = '\x1B[';

  /// 重置当前SGRS的所有颜色和选项为终端默认值。
  static const ansiDefault = '${ansiEsc}0m';

  final int? fg;
  final int? bg;
  final bool color;

  AnsiColor.none()
      : fg = null,
        bg = null,
        color = false;

  AnsiColor.fg(this.fg)
      : bg = null,
        color = true;

  AnsiColor.bg(this.bg)
      : fg = null,
        color = true;

  @override
  String toString() {
    if (fg != null) {
      return '${ansiEsc}38;5;${fg}m';
    } else if (bg != null) {
      return '${ansiEsc}48;5;${bg}m';
    } else {
      return '';
    }
  }

  String call(String msg) {
    if (color) {
      // ignore: unnecessary_brace_in_string_interps
      return '${this}$msg$ansiDefault';
    } else {
      return msg;
    }
  }

  AnsiColor toFg() => AnsiColor.fg(bg);

  AnsiColor toBg() => AnsiColor.bg(fg);

  String get resetForeground => color ? '${ansiEsc}39m' : '';

  String get resetBackground => color ? '${ansiEsc}49m' : '';

  static get debuger => List.generate(255, (index) {
        final color = AnsiColor.fg(index);
        stdout.writeln(color("$index index"));
      }).toList();

  static AnsiColor get debug => AnsiColor.fg(4);
  static AnsiColor get info => AnsiColor.fg(2);
  static AnsiColor get warning => AnsiColor.fg(3);
  static AnsiColor get error => AnsiColor.fg(1);
  static AnsiColor get verbose => AnsiColor.fg(5);
  static AnsiColor get def => AnsiColor.fg(6);
}
